有時候還是會有意外,但是出現問題如果跑出奇怪的錯有可能讓前端措手不及,或是稍微偽裝一下,可以讓客戶端無感異常
起動程式增加 @EnableCircuitBreaker ,然後在需要此功能的方法上增加 @HystrixCommand(fallbackMethod = "getReservationNamesFallback") 當失敗時他就會使用你指定的方法 getReservationNamesFallback 來回覆前端
@EnableZuulProxy
@EnableBinding(Source.class)
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ReservationClientApplication {
public static void main(String[] args) {
SpringApplication.run(ReservationClientApplication.class, args);
}
}
@RestController
@RequestMapping("/reservations")
class ReservationApiGatewayRestController{
@Autowired
@LoadBalanced
private RestTemplate restTemplate;
@Autowired
@Output(Source.OUTPUT)
private MessageChannel messageChannel;
@RequestMapping( method = RequestMethod.POST)
public void write(@RequestBody Reservation r){
this.messageChannel.send(MessageBuilder.withPayload(r.getReservationName()).build());
}
public Collection<String> getReservationNamesFallback(){
return Collections.emptyList();
}
@HystrixCommand(fallbackMethod = "getReservationNamesFallback")
@RequestMapping("names")
public Collection<String> getReservationNames(){
ParameterizedTypeReference<Resources<Reservation>> ptr =
new ParameterizedTypeReference<Resources<Reservation>>(){};
ResponseEntity<Resources<Reservation>> responseEntity =
this.restTemplate.exchange("http://reservation-service/reservations",
HttpMethod.GET, null, ptr);
Collection<String> nameList = responseEntity
.getBody()
.getContent()
.stream()
.map(Reservation::getReservationName)
.collect(Collectors.toList());
return nameList;
}
}
reservation-client 起動後,把 reservation-service 關掉,這麼一來通常應用程式就會發生異常回傳 500 之類的,但是你可以試著呼叫 http://localhost:8050/reservations/names,你可以發現你只是得到一個空集合,不影響你的前端程式
[]